/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mytdev.commons.text.parsers;

import com.mytdev.commons.text.AbstractParser;
import com.mytdev.commons.util.StringConstants;
import java.awt.Font;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 *
 * @author Yann D'Isanto
 */
public class FontParser extends AbstractParser<Font> {

    private static final Map<String, Integer> FONT_STYLES = new HashMap<String, Integer>();

    static {
        FONT_STYLES.put("bold", Font.BOLD);
        FONT_STYLES.put("italic", Font.ITALIC);
        FONT_STYLES.put("plain", Font.PLAIN);
    }

    public FontParser() {
        super(Font.class);
    }

    @Override
    public Font parse(String string) throws ParseException {
        // TODO: check if valid string, throw ParseException if not
        String[] fontProperties = string.split(Pattern.quote(StringConstants.COMMA));
        String name = fontProperties[0].trim();
        int style = Font.PLAIN;
        String styleProperty = fontProperties[1].trim();
        if (!styleProperty.isEmpty()) {
            String[] styles = styleProperty.split(StringConstants.SPACE);
            for (String fontStyle : styles) {
                style |= FONT_STYLES.get(fontStyle);
            }
        }
        int size = Integer.parseInt(fontProperties[2].trim());
        return new Font(name, style, size);
    }
}
